﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

namespace Core
{
    public static class Log
    {
        public static LogLevel Level { get; set; } = LogLevel.Info;

        static Log()
        {
            Application.logMessageReceivedThreaded -= LogMessageReceivedThreaded;
            Application.logMessageReceivedThreaded += LogMessageReceivedThreaded;
        }

        private static void LogMessageReceivedThreaded(string condition, string stackTrace, LogType type)
        {
            var level = LogLevel.None;
            switch (type)
            {
                case LogType.Log:
                    level = LogLevel.Info;
                    break;
                case LogType.Warning:
                    level = LogLevel.Warning;
                    break;
                case LogType.Error:
                    level = LogLevel.Error;
                    break;
            }

            new SaveLog(condition, stackTrace, level).Publish();
        }

        public static void Info(object message)
        {
            if (LogLevel.Info < Level)
            {
                new SaveLog(message.ToString(), "", LogLevel.Info).Publish();
                return;
            }

            Debug.Log(message);
        }

        public static void Warning(object message)
        {
            if (LogLevel.Warning < Level)
            {
                new SaveLog(message.ToString(), "", LogLevel.Warning).Publish();
                return;
            }

            Debug.LogWarning(message);
        }

        public static void ImportantInfo(object message)
        {
            Debug.Log(message);
        }

        public static void Error(object message)
        {
            Debug.LogError(message);
        }
    }

    public enum LogLevel
    {
        None,
        Info,
        Warning,
        ImportantInfo,
        Error,
    }

    public struct SaveLog : IEventData
    {
        public string condition;
        public string stackTrace;
        public LogLevel level;

        public SaveLog(string  condition, string stackTrace, LogLevel level)
        {
            this.condition = condition;
            this.stackTrace = stackTrace;
            this.level = level;
        }
    }
}
